#include "user_switch.h"
#include "ui_user_switch.h"

UserSwitch::UserSwitch(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::UserSwitch)
{
    ui->setupUi(this);

    connect(ui->pb_userSwitchReturnMenu, &QPushButton::clicked, this, &UserSwitch::pushReturnMenu);

    setupUiAppearance();
    connectUserButtons();
    connectUiButtons();
}

void UserSwitch::setupUiAppearance()
{
    ui->widget->setAutoFillBackground(true);
    QPalette palette = ui->widget->palette();
    palette.setColor(QPalette::Background, Qt::white);
    ui->widget->setPalette(palette);
    ui->label_userLevel->setText(userLevel);

    ui->widget_2->hide();
}

void UserSwitch::connectUserButtons()
{
    QPushButton* userButtons[4] = {ui->pb_user1, ui->pb_user2, ui->pb_user3, ui->pb_user4};

    for (int i = 0; i < 4; ++i) {
        connect(userButtons[i], &QPushButton::clicked, this, [this, i]() {
            onUserButtonClicked(i + 1);
        });
    }
}

void UserSwitch::connectUiButtons()
{
    connect(ui->toolButton_15, &softkeys::close_windows, this, &UserSwitch::hideWidget);
    connect(ui->toolButton_17, &softkeys::close_windows, this, &UserSwitch::onSwitchUser);
}

void UserSwitch::onUserButtonClicked(int userNumber)
{
    pbUserClicked = userNumber;
    ui->widget_2->show();
    ui->lineEdit->setFocus();
}

void UserSwitch::hideWidget()
{
    ui->widget_2->hide();
}

void UserSwitch::onSwitchUser()
{
   hideWidget();
    if (isPasswordRight(pbUserClicked)) {
        QString pbUserClickedStr = QString::number(pbUserClicked, 10);
        ui->label_userLevel->setText(pbUserClickedStr);
        userLevel = pbUserClickedStr;
    }
    ui->lineEdit->setText("");
}

bool UserSwitch::isPasswordRight(const int &pbUserClicked)
{
    QString tempPwd = ui->lineEdit->text();
    for (int i = 0; i < 4; i++) {
        if (tempPwd == userPasswd[i] && pbUserClicked == i + 1) {
            return true;
        }
    }
    return false;
}

UserSwitch::~UserSwitch()
{
    delete ui;
}

void UserSwitch::pushReturnMenu()
{
    emit returnMenu();
}
